package com.retail.admin.controller;

import com.retail.admin.dto.LoginRequest;
import com.retail.admin.dto.LoginResponse;
import com.retail.admin.dto.UserInfo;
import com.retail.admin.service.AuthService;
import com.retail.common.result.Result;
import com.retail.common.utils.JwtUtils;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 *
 * @author retail
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private static final Logger log = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("/login")
    public Result<LoginResponse> login(@Valid @RequestBody LoginRequest loginRequest) {
        log.info("用户登录请求，用户名：{}", loginRequest.getUsername());
        
        try {
            LoginResponse response = authService.login(loginRequest);
            log.info("用户登录成功，用户ID：{}", response.getUserInfo().getId());
            return Result.success(response);
        } catch (Exception e) {
            log.error("用户登录失败，用户名：{}，错误：{}", loginRequest.getUsername(), e.getMessage());
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/userInfo")
    public Result<UserInfo> getUserInfo(@RequestHeader("Authorization") String authorization) {
        try {
            // 从Authorization头中提取token
            String token = authorization.replace("Bearer ", "");
            
            // 验证token
            if (!jwtUtils.validateToken(token)) {
                return Result.error("Token无效");
            }

            // 从token中获取用户ID
            Long userId = jwtUtils.getClaimFromToken(token, "userId", Long.class);
            if (userId == null) {
                return Result.error("Token中缺少用户ID");
            }

            // 从数据库获取用户信息
            UserInfo userInfo = authService.getUserInfo(userId);
            return Result.success(userInfo);
        } catch (Exception e) {
            log.error("获取用户信息失败，错误：{}", e.getMessage());
            return Result.error("获取用户信息失败");
        }
    }

    @PostMapping("/logout")
    public Result<Boolean> logout() {
        // 实际应用中可能需要使JWT Token失效
        return Result.success(true);
    }

    @PostMapping("/refresh")
    public Result<Map<String, String>> refreshToken(@RequestHeader("Authorization") String authorization) {
        try {
            String token = authorization.replace("Bearer ", "");
            
            if (!jwtUtils.validateToken(token)) {
                return Result.error("Token无效");
            }

            String newToken = jwtUtils.refreshToken(token);
            if (newToken != null) {
                Map<String, String> result = new HashMap<>();
                result.put("token", newToken);
                return Result.success(result);
            } else {
                return Result.error("刷新Token失败");
            }
        } catch (Exception e) {
            log.error("刷新Token失败，错误：{}", e.getMessage());
            return Result.error("刷新Token失败");
        }
    }

    @GetMapping("/health")
    public Result<Map<String, Object>> health() {
        Map<String, Object> health = new HashMap<>();
        health.put("status", "UP");
        health.put("timestamp", System.currentTimeMillis());
        health.put("service", "retail-admin");
        return Result.success(health);
    }
}